// Package configs 配置文件读取
package configs

import (
	"github.com/go-ini/ini"
	"os"
	"strings"
)

var (
	RedisConfig = map[string]string{}
	DbConfig    = map[string]string{}
)

// GetDbConfig 数据库配置
func GetDbConfig() map[string]string {
	if _, ok := DbConfig["DB_HOST"]; ok {
		return DbConfig
	}
	pa, _ := os.Getwd()
	GetDirectory := strings.Replace(pa, "\\", "/", -1)
	configFilePath := GetDirectory + "/conf.ini"

	Cfg, err := ini.Load(configFilePath) //此路径为ini文件的路径
	if err != nil {
		panic("读取ini配置文件失败")
	}
	section := Cfg.Section("Database")

	// 初始化数据库配置map
	dbConfig := make(map[string]string)

	dbConfig["DB_HOST"] = section.Key("Host").String()
	dbConfig["DB_PORT"] = section.Key("Port").String()
	dbConfig["DB_NAME"] = section.Key("Name").String()
	dbConfig["DB_USER"] = section.Key("User").String()
	dbConfig["DB_PWD"] = section.Key("Password").String()
	dbConfig["DB_CHARSET"] = "utf8"
	dbConfig["DB_PREFIX"] = section.Key("TablePrefix").String()

	dbConfig["DB_MAX_OPEN_CONNS"] = "20"       // 连接池最大连接数
	dbConfig["DB_MAX_IDLE_CONNS"] = "20"       // 连接池最大空闲数
	dbConfig["DB_MAX_LIFETIME_CONNS"] = "7200" // 连接池链接最长生命周期

	DbConfig = dbConfig
	return DbConfig
}

// GetRedisConfig Redis配置
func GetRedisConfig() map[string]string {
	if _, ok := RedisConfig["RDS_SERVER"]; ok {
		return RedisConfig
	}
	pa, _ := os.Getwd()
	GetDirectory := strings.Replace(pa, "\\", "/", -1)
	configFilePath := GetDirectory + "/conf.ini"

	Cfg, err := ini.Load(configFilePath) //此路径为ini文件的路径
	if err != nil {
		panic("读取ini配置文件失败")
	}
	section := Cfg.Section("Redis")

	// 初始化数据库配置map
	rdsConfig := make(map[string]string)
	rdsConfig["RDS_SERVER"] = section.Key("Server").String()
	rdsConfig["RDS_PWD"] = section.Key("Password").String()
	rdsConfig["RDS_DB"] = section.Key("DB").String()

	rdsConfig["RDS_NETWORK"] = "tcp"

	RedisConfig = rdsConfig
	return RedisConfig
}
